package com.hgkx.service.impl;

import com.alibaba.fastjson.JSON;
import com.hgkx.domain.UploadFile;
import com.hgkx.service.UploadFileService;
import com.hgkx.util.FilePath;
import com.hgkx.util.FilePathUtil;
import com.hgkx.util.FileUploadUtil;
import com.hgkx.util.FileUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Override
    public String upload(MultipartFile uploadFile, HttpServletRequest req) {
        //找到要上传的地址
        String path= FilePath.Files;
        //完善地址 加"/"
        path= FilePathUtil.pathLast(path);
        //把文件上传
        UploadFile fileData = FileUploadUtil.uploadPahtFileAndUploadFile(uploadFile, path, req);
        //添加到文件记录表中
        FileUtil.writeFile(FilePath.UPLOADFILE, JSON.toJSONString(fileData));
        //将访问地址返回
        return fileData.getPath();
    }

    @Override
    public List<String> uploads(MultipartFile[] uploads, HttpServletRequest req) {
        //找到要上传的地址
        String path=FilePath.Files;
        path=FilePathUtil.pathLast(path);
        List<UploadFile> list=FileUploadUtil.uploadPahtFiles(uploads,path,req);
        List<String> paths=new ArrayList<>();
        for (UploadFile upload:list){
            //获取访问路径
            paths.add(upload.getPath());
            //将文件对象转为json
            FileUtil.writeFile(FilePath.UPLOADFILE,JSON.toJSONString(upload));
        }
        return paths;
    }
}
